package fr.sedoo.metadata.client.ui.widget.dialog.format;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ListBox;

import fr.sedoo.commons.client.callback.LoadCallBack;
import fr.sedoo.commons.client.event.ActionEventConstants;
import fr.sedoo.commons.client.event.ActionStartEvent;
import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.widget.DialogBoxTools;
import fr.sedoo.metadata.client.service.FormatService;
import fr.sedoo.metadata.client.service.FormatServiceAsync;
import fr.sedoo.metadata.shared.domain.dto.FormatDTO;

public class ClientFormatList {

	private final static FormatServiceAsync FORMAT_SERVICE = GWT.create(FormatService.class);
	private static ListBox listBox = new ListBox();
	private static boolean loaded = false;
	private static ArrayList<LoadCallBack> callBacks = new ArrayList<LoadCallBack>();
	private static EventBus eventBus;

	public static void setEventBus(EventBus eventBus) {
		ClientFormatList.eventBus = eventBus;
	}

	public static void getFormats(LoadCallBack callBack) {
		if (loaded) {
			callBack.postLoadProcess(listBox);
		} else {
			callBacks.add(callBack);
			loadFormats();
		}
	}

	public static void loadFormats() {
		final ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstants.BASIC_LOADING_EVENT, true);
		eventBus.fireEvent(e);

		FORMAT_SERVICE.findAll(new AsyncCallback<ArrayList<FormatDTO>>() {

			@Override
			public void onSuccess(ArrayList<FormatDTO> formats) {

				Iterator<FormatDTO> iterator = formats.iterator();

				while (iterator.hasNext()) {
					FormatDTO current = (FormatDTO) iterator.next();
					listBox.addItem(current.getName());
					List<String> versions = current.getVersions();
					Iterator<String> versionIterator = versions.iterator();
					while (versionIterator.hasNext()) {
						String currentVersion = versionIterator.next();
						listBox.addItem(current.getName() + " " + currentVersion, current.getName() + "@" + currentVersion);
					}

				}
				eventBus.fireEvent(e.getEndingEvent());
				loaded = true;
				Iterator<LoadCallBack> secondIterator = callBacks.iterator();
				while (secondIterator.hasNext()) {
					getFormats(secondIterator.next());
				}
				callBacks.clear();
			}

			@Override
			public void onFailure(Throwable caught) {
				DialogBoxTools.modalAlert(CommonMessages.INSTANCE.error(), CommonMessages.INSTANCE.anErrorHasOccurred() + " : " + caught.getMessage());
			}
		});

	}

}
